package com.persondemo.videoappliction.ui.vip;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.persondemo.videoappliction.R;
import com.persondemo.videoappliction.bean.PuShopBean;
import com.persondemo.videoappliction.bean.PutShopTypeBean;
import com.persondemo.videoappliction.bean.UpimgBean;
import com.persondemo.videoappliction.component.ApplicationComponent;
import com.persondemo.videoappliction.component.DaggerHttpComponent;
import com.persondemo.videoappliction.event.PutShopEvent;
import com.persondemo.videoappliction.photo.PhotoPickerActivity;
import com.persondemo.videoappliction.ui.adapter.PutShopTypeAdapter;
import com.persondemo.videoappliction.ui.base.AppManager;
import com.persondemo.videoappliction.ui.base.BaseActivity;
import com.persondemo.videoappliction.ui.vip.contract.PutShopContract;
import com.persondemo.videoappliction.ui.vip.presenter.PutShopPresenter;
import com.persondemo.videoappliction.utils.ImageLoaderUtil;
import com.persondemo.videoappliction.utils.PreferenceUtil;
import com.persondemo.videoappliction.utils.T;
import com.persondemo.videoappliction.utils.ViewFindUtils;

import org.simple.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class PutShopActivity extends BaseActivity<PutShopPresenter> implements PutShopContract.View {
    @BindView(R.id.putshop_back)
    ImageView putshopBack;
    @BindView(R.id.putshop)
    TextView putshop;
    @BindView(R.id.putshop_name_edit)
    EditText putshopNameEdit;
    @BindView(R.id.putshop_adress_edit)
    EditText putshopAdressEdit;
    @BindView(R.id.putshop_phone)
    EditText putshopPhone;
    @BindView(R.id.putshop_type)
    TextView putshopType;
    @BindView(R.id.putshop_adress_02)
    EditText putshopAdress02;
    @BindView(R.id.putshop_img)
    ImageView putshopImg;
    @BindView(R.id.time_edit)
    EditText timeEdit;
    @BindView(R.id.renjun_edit)
    EditText renjunEdit;
    private String img = "", type = "";
    private List<PutShopTypeBean.DataBean> list01;
    private View view01;
    private PopupWindow window01;
    private RecyclerView cycler_dianping_01;
    PutShopTypeAdapter ad01;//分类
    // 屏幕的width
    private int mScreenWidth;
    // 屏幕的height
    private int mScreenHeight;
    private String imei = "";

    @Override
    public void onRetry() {

    }

    @Override
    public int getContentLayout() {
        return R.layout.module_activity_putshop;
    }

    @Override
    public void initInjector(ApplicationComponent appComponent) {
        DaggerHttpComponent.builder()
                .applicationComponent(appComponent)
                .build()
                .inject(this);
    }

    @Override
    public void bindView(View view, Bundle savedInstanceState) {
        putshopPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().trim().length() == 11) {
                    T.showShort(PutShopActivity.this, "电话号码最多11位！");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    public void initData() {
        list01 = new ArrayList<>();
        if (mPresenter != null) {
            mPresenter.gettype();
        }
    }

    @Override
    public void loadshop(PuShopBean puShopBean) {
        if (puShopBean.getStatus() == 1) {
            T.showShort(PutShopActivity.this, puShopBean.getMsg());
            EventBus.getDefault().post(new PutShopEvent("1"));
            AppManager.getAppManager().finishActivity();
        } else {
            T.showShort(PutShopActivity.this, puShopBean.getMsg());
        }
    }

    @Override
    public void imgdata(UpimgBean upimgBean) {
        hideLoadingDialog();
        if (upimgBean.getStatus() == 1) {
            if (TextUtils.isEmpty(img)) {
                img = upimgBean.getData();
            } else {
                img = img + "," + upimgBean.getData();
            }
            T.showShort(PutShopActivity.this, upimgBean.getMsg());

        } else {
            T.showShort(PutShopActivity.this, upimgBean.getMsg() + "请重新上传图片！");
        }
    }

    @Override
    public void loadtype(PutShopTypeBean putShopTypeBean) {
        if (putShopTypeBean.getStatus() == 1 && putShopTypeBean.getData().size() > 0) {
            list01 = putShopTypeBean.getData();
        } else {
            T.showShort(PutShopActivity.this, putShopTypeBean.getMsg());
        }
    }

    //类型筛选
    private void showpop01() {
        mScreenWidth = getWindowManager().getDefaultDisplay().getWidth();
        mScreenHeight = getWindowManager().getDefaultDisplay().getHeight();
        view01 = getLayoutInflater().inflate(R.layout.module_pop_dianping01, null);
        cycler_dianping_01 = view01.findViewById(R.id.cycler_dianping_01);
        ad01 = new PutShopTypeAdapter(list01);
        cycler_dianping_01.setAdapter(ad01);
        cycler_dianping_01.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
        ad01.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                for (int i = 0; i < list01.size(); i++) {
                    list01.get(i).setIscheck(false);
                }
                putshopType.setText(list01.get(position).getName());
                list01.get(position).setIscheck(true);
                type = list01.get(position).getId() + "";
                window01.dismiss();
            }
        });

        window01 = new PopupWindow(view01, mScreenWidth * 9 / 10, mScreenHeight * 9 / 10, true);
        //        设置popwindow如果点击外面区域，便关闭。
        window01.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        window01.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        window01.showAtLocation(view01, Gravity.CENTER, 0, 0);
        window01.setBackgroundDrawable(new BitmapDrawable());
        //将这两个属性设置为false，使点击popupwindow外面其他地方会消失
        window01.setOutsideTouchable(true);
        window01.setFocusable(true);
        setlayoutColor();
        window01.update();


        window01.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                getlayoutColor();
            }
        });
    }

    /*
     * 改变背景颜色亮度,当点击window让屏幕变暗
     */
    protected void setlayoutColor() {
        Float A = (float) .10f;
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.7f;
        getWindow().setAttributes(lp);
    }

    /*
     * 恢复背景颜色亮度
     */
    protected void getlayoutColor() {
        Float A = (float) 1f;
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 1f;
        getWindow().setAttributes(lp);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.putshop_back, R.id.putshop_img, R.id.putshop_type, R.id.putshop})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.putshop_back:
                AppManager.getAppManager().finishActivity();
                break;
            case R.id.putshop_img:
                Intent intent = new Intent(PutShopActivity.this, PhotoPickerActivity.class);
                intent.putExtra(PhotoPickerActivity.EXTRA_SHOW_CAMERA, true);
                intent.putExtra(PhotoPickerActivity.EXTRA_SELECT_MODE, PhotoPickerActivity.MODE_MULTI);
                intent.putExtra(PhotoPickerActivity.EXTRA_MAX_MUN, 1);
                startActivityForResult(intent, 1);
                break;
            case R.id.putshop:
                upshop();
                break;
            case R.id.putshop_type:
                showpop01();
                break;
        }
    }

    private void upshop() {
        String name = putshopNameEdit.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            T.showShort(PutShopActivity.this, "请填写商家名称");
            return;
        }
        String address = putshopAdressEdit.getText().toString().trim();
        if (TextUtils.isEmpty(address)) {
            T.showShort(PutShopActivity.this, "请填写商家地址");
            return;
        }
        String phone = putshopPhone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            T.showShort(PutShopActivity.this, "请填写商家电话");
            return;
        }
        String time = timeEdit.getText().toString().trim();
        if (TextUtils.isEmpty(time)) {
            T.showShort(PutShopActivity.this, "请填写营业时间");
            return;
        }
        if (TextUtils.isEmpty(putshopType.getText().toString().trim())) {
            T.showShort(PutShopActivity.this, "请输入商家分类");
            return;
        }
        String adress02 = putshopAdress02.getText().toString().trim();
        if (TextUtils.isEmpty(adress02)) {
            T.showShort(PutShopActivity.this, "请输入商业地址");
            return;
        }
        String renjun = renjunEdit.getText().toString().trim();
        if (TextUtils.isEmpty(renjun)) {
            T.showShort(PutShopActivity.this, "请输入人均消费");
            return;
        }
        imei = PreferenceUtil.getString("imei", "");
        if (TextUtils.isEmpty(imei)) {
            T.showShort(PutShopActivity.this, "未获取到imei权限，请从设置打开授予权限！");
            return;
        }
        if (mPresenter != null) {
            mPresenter.putshop(name, adress02, renjun, phone, time, address, img, type, imei);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                ArrayList<String> result = data.getStringArrayListExtra(PhotoPickerActivity.KEY_RESULT);
                yasuo(result);
            }
        }
    }

    private String getPath() {
        String path = Environment.getExternalStorageDirectory() + "/Luban/image/";
        File file = new File(path);
        if (file.mkdirs()) {
            return path;
        }
        return path;
    }

    private void yasuo(ArrayList<String> photos) {
        ImageLoaderUtil.LoadImage(PutShopActivity.this, photos.get(0), putshopImg);
        Luban.with(this)
                .load(photos)
                .ignoreBy(100)
                .setTargetDir(getPath())
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(File file) {
                        Log.i("lidaming", "11");
                        if (mPresenter != null) {
                            RequestBody requestFile =
                                    RequestBody.create(MediaType.parse("multipart/form-data"), file);
                            MultipartBody.Part body =
                                    MultipartBody.Part.createFormData("imgs", file.getName(), requestFile);
                            showLoadingDialog("图片上传中。。。");
                            mPresenter.upimgdata(body);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                    }
                }).launch();
    }

}
